<!--
 * @Author: 冕上 cxm66888@163.com
 * @Date: 2025-06-21 14:04:33
 * @LastEditors: 冕上 cxm66888@163.com
 * @LastEditTime: 2025-06-23 12:45:43
 * @Description: 
 * 
 * Copyright (c) 2025 by xiaoMing.Cao, All Rights Reserved. 
-->

<template>
  <div class="api-logs">
    <div class="api-logs-head">
      <el-form :inline="true" :model="data.form" class="demo-form-inline">
        <el-form-item label="日期">
          <el-date-picker v-model="data.form.date" type="date" placeholder="选择日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="路径">
          <el-input v-model="data.form.path" placeholder="请输入API路径" />
        </el-form-item>
        <el-form-item label="方法">
          <el-select v-model="data.form.method" placeholder="请选择请求方法">
            <el-option label="全部" value="" />
            <el-option label="GET" value="GET" />
            <el-option label="POST" value="POST" />
            <el-option label="PUT" value="PUT" />
            <el-option label="DELETE" value="DELETE" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态码">
          <el-input v-model="data.form.status" placeholder="请输入状态码" />
        </el-form-item>
        <el-form-item label="用户ID">
          <el-input v-model="data.form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="IP地址">
          <el-input v-model="data.form.ip" placeholder="请输入IP地址" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">查询</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button type="info" @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- API失败请求详情表格 -->
    <div class="api-logs-main">
      <el-table :data="data.list" style="width: 100%" v-loading="loading">
        <el-table-column prop="path" label="API路径" min-width="180" show-overflow-tooltip />
        <el-table-column prop="method" label="请求方法" width="80" align="center" />
        <el-table-column prop="status" label="状态码" width="80" align="center" />
        <el-table-column prop="userId" label="用户ID" width="100" align="center" show-overflow-tooltip />
        <el-table-column prop="ip" label="IP地址" width="120" align="center" show-overflow-tooltip />
        <el-table-column prop="timestamp" label="时间" width="180" align="center">
          <template #default="scope">
            {{ dayjs(scope.row.timestamp).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
        </el-table-column>
        <el-table-column prop="error" label="错误信息" min-width="200" show-overflow-tooltip />
        <el-table-column label="详情" width="80" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" @click="viewDetail(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination style="margin-top: 15px" :page-size="parament.limit" @current-change="pageChange" background layout="prev, pager, next" :total="data.total" />
    </div>

    <!-- 详情弹窗 -->
    <el-dialog v-model="dialogVisible" title="请求详情" width="60%">
      <div v-if="currentDetail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="请求路径">{{ currentDetail.path }}</el-descriptions-item>
          <el-descriptions-item label="请求方法">{{ currentDetail.method }}</el-descriptions-item>
          <el-descriptions-item label="状态码">{{ currentDetail.status }}</el-descriptions-item>
          <el-descriptions-item label="用户ID">{{ currentDetail.userId }}</el-descriptions-item>
          <el-descriptions-item label="IP地址">{{ currentDetail.ip }}</el-descriptions-item>
          <el-descriptions-item label="请求时间">
            {{ dayjs(currentDetail.timestamp).format('YYYY-MM-DD HH:mm:ss') }}
          </el-descriptions-item>
          <el-descriptions-item label="错误信息">{{ currentDetail.error }}</el-descriptions-item>
          <el-descriptions-item label="请求参数">
            <pre>{{ formatJson(currentDetail.requestParams) }}</pre>
          </el-descriptions-item>
          <el-descriptions-item label="响应内容">
            <pre>{{ formatJson(currentDetail.response) }}</pre>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
  import { onMounted, reactive, ref } from 'vue';
  import { useRouter, useRoute } from 'vue-router';
  import { getApiFailLogs } from '@/api/apiLogs';
  import { ElMessage } from 'element-plus';
  import dayjs from 'dayjs';

  // 添加组件名称，用于keep-alive
  defineOptions({
    name: 'ApiFailLogs'
  });

  const router = useRouter();
  const route = useRoute();
  const loading = ref(false);
  const dialogVisible = ref(false);
  const currentDetail = ref(null);

  const data = reactive({
    list: [],
    total: 0,
    form: {
      date: '',
      path: '',
      method: '',
      status: '',
      userId: '',
      ip: ''
    }
  });

  const parament = reactive({
    page: 0,
    limit: 50
  });

  // 获取API失败请求详情
  const getList = () => {
    loading.value = true;
    getApiFailLogs({ ...data.form, ...parament })
      .then(res => {
        if (res.code === 200) {
          data.list = res.data?.data || [];
          data.total = res.data?.total || 0;
        } else {
          ElMessage.error(res.message || '获取数据失败');
        }
      })
      .catch(err => {
        console.error('获取API失败请求详情失败', err);
        ElMessage.error('获取API失败请求详情失败');
      })
      .finally(() => {
        loading.value = false;
      });
  };

  // 查看详情
  const viewDetail = row => {
    currentDetail.value = row;
    dialogVisible.value = true;
  };

  // 格式化JSON
  const formatJson = json => {
    if (!json) return '';
    try {
      if (typeof json === 'string') {
        return JSON.stringify(JSON.parse(json), null, 2);
      } else {
        return JSON.stringify(json, null, 2);
      }
    } catch (e) {
      return json;
    }
  };

  // 返回上一页
  const goBack = () => {
    router.back();
  };

  const submitForm = () => {
    parament.page = 0;
    getList();
  };

  const resetForm = () => {
    data.form = {
      date: '',
      path: '',
      method: '',
      status: '',
      userId: '',
      ip: ''
    };
    getList();
  };

  const pageChange = page => {
    parament.page = page - 1;
    getList();
  };

  onMounted(() => {
    // 从路由参数中获取查询条件
    const { path, method, date } = route.query;
    if (path) data.form.path = path;
    if (method) data.form.method = method;
    if (date) data.form.date = date;

    getList();
  });
</script>

<style scoped lang="scss">
  .api-logs {
    padding: 15px;
    width: 100%;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;

    .api-logs-head,
    .api-logs-main {
      background-color: #fff;
      display: flex;
      padding: 15px;
      box-sizing: border-box;
      width: 100%;
      margin-bottom: 15px;
      flex-direction: column;
    }
  }

  .demo-form-inline .el-input {
    --el-input-width: 180px;
  }

  .demo-form-inline .el-select {
    --el-select-width: 180px;
  }

  .el-table__header {
    background-color: #d3e3fd;
  }

  pre {
    background-color: #f5f7fa;
    padding: 10px;
    border-radius: 4px;
    overflow: auto;
    max-height: 300px;
    margin: 0;
    // 英文自动换行
    white-space: pre-wrap; /* 保留格式的同时允许换行 */
    word-break: break-word; /* 对于长单词或连续字符进行换行 */
  }
</style>
